package com.chzu.controller;

import com.chzu.pojo.SignSubmission;
import com.chzu.pojo.SysUser;
import com.chzu.result.JsonResult;
import com.chzu.service.SignSubmissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author lz
 * @Version 1.0
 * @Company 滁州大健康与养老产业研究院
 * @ClassName SignSubmissionController
 * @Description TODO
 * @Date 2022/02/13 19:59
 */
@RestController
@RequestMapping("/signSubmission")
@Api(tags = "活动签到以及感想的接口")
public class SignSubmissionController {

    @Resource
    private SignSubmissionService signSubmissionService;

    @ApiOperation("添加签到以及提交感想情况")
    @Transactional(rollbackFor= Exception.class)
    @PostMapping("/")
    public JsonResult<String> addSingleInstance(@RequestBody SignSubmission signSubmission) {
        SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        signSubmission.setCreateTime(new Date());
        signSubmission.setUserName(user.getUsername());
        signSubmission.setOpenId(user.getOpenId());
        boolean res = signSubmissionService.save(signSubmission);
        if (!res) {
            return JsonResult.fail("添加失败");
        }
        return JsonResult.ok("添加成功");
    }

    @ApiOperation("删除签到以及提交感想情况")
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/{id}")
    public JsonResult<String> deleteSingleInstance(@PathVariable Long id) {
        Boolean res = signSubmissionService.deleteSingleInstanceById(id);
        if (!res) {
            return JsonResult.fail("删除失败");
        }
        return JsonResult.ok("删除成功");
    }

    @ApiOperation("修改签到以及提交感想情况")
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/")
    public JsonResult<String> updateSingleInstance(@RequestBody SignSubmission signSubmission) {
        boolean res = signSubmissionService.updateById(signSubmission);
        if (!res) {
            return JsonResult.fail("更新失败");
        }
        return JsonResult.ok("更新成功");
    }

    @ApiOperation("获取所有签到以及提交感想情况")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/")
    public JsonResult<List<SignSubmission>> getAllSingleInstance() {
        List<SignSubmission> data = signSubmissionService.list();
        return JsonResult.ok(data);
    }

    @ApiOperation("获取活动的签到人数")
    @GetMapping("/getSignByActivityId/{activityId}")
    public JsonResult<Object> getSignByActivityId(@PathVariable("activityId") String activityId) {
        Long data = signSubmissionService.getSignByActivityId(activityId);
        return JsonResult.ok(data);
    }
}
